import os
from pdf2image import convert_from_path
import cv2
import numpy as np

# PDF文件所在目录
pdf_directory = r'D:\NodeTest\pdf'

# 遍历目录中的所有文件
for filename in os.listdir(pdf_directory):
  if filename.lower().endswith('.pdf'):
    pdf_path = os.path.join(pdf_directory, filename)
    print(f"\nProcessing PDF: {pdf_path}")

    # 指定 poppler 路径
    poppler_path = r'D:\poppler-24.08.0\Library\bin'

    try:
      pages = convert_from_path(pdf_path, poppler_path = poppler_path)
      print(f"成功转换PDF，共 {len(pages)} 页")

      # 生成基于 PDF 文件名的子目录
      pdf_name = os.path.splitext(filename)[0].replace(" ", "_")
      output_dir = os.path.join(pdf_directory, pdf_name)
      os.makedirs(output_dir, exist_ok = True)
      print(f"输出目录: {output_dir}")

      for page_number, page in enumerate(pages, start = 1):
        # 将图片保存为 OpenCV 格式
        cv_image = cv2.cvtColor(np.array(page), cv2.COLOR_RGB2BGR)

        # 检查图像数据
        if cv_image is None or cv_image.size == 0:
          print(f"第 {page_number} 页图像数据无效!")
          continue

        # 生成图片名称
        image_name = f"{pdf_name}_{page_number}.jpg"
        image_path = os.path.join(output_dir, image_name)
        # print(f"尝试保存图片到: {image_path}")

        # 尝试保存
        page.save(os.path.join(output_dir, image_path), "JPEG")
        print(f"尝试用PIL保存成功: {image_path}")
        # try:
        #   success = cv2.imwrite(image_path, cv_image)
        #   if success:
        #     print(f"成功保存: {image_path}")
        #   else:
        #     print(f"保存失败: {image_path}")
        #     page.save(os.path.join(output_dir, image_path), "JPEG")
        #     print("尝试用PIL保存成功")
        # except Exception as e:
        #   print(f"保存时出错: {str(e)}")

    except Exception as e:
      print(f"处理PDF时出错: {str(e)}")
